<%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@include file="../WEB-INF/jspf/controlesessao.jspf"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Nova Turma</title>
        <script type="text/javascript" src="../js/jquery.js" ></script>
        <script type="text/javascript" src="../js/jquery-ui-1.8.2.custom.min.js" ></script>
        <script type="text/javascript" src="../js/jquery.ui.datepicker-pt-BR.js" ></script>
        <link rel="stylesheet" type="text/css" media="screen" href="../css/ui.jqgrid.css" />
        <script src="../js/i18n/grid.locale-pt-br.js" type="text/javascript"></script>
        <script src="../js/jquery.jqGrid.src.js" type="text/javascript"></script>
        <script type="text/javascript" src="../js/jquery.validate.js"></script>
        <script type="text/javascript" src="../js/forms.js"></script>
        <script type="text/javascript" src="../js/alocacao.js"></script>
        <link rel="stylesheet" href="../css/forms.css">
        <link rel="stylesheet" href="../css/ui-lightness/jquery-ui-1.8.2.custom.css">
    </head>
    <script>
        $(document).ready(function() {
            $("#form").validate({
                rules: {
                    matricula: {required: true}
                    , id_turno: {required: true, digits: true
                    }
                    , data_inicio: {required: true, date: true
                    }
                    , data_fim: {required: true, date: true
                    }
                },
                submitHandler: function(form) {
                    salvar(form);
                }
            });


        });
        function clicar(acao) {
            $("#operacao").val(acao);
        }

        $(function() {
            $('#data_inicio').datepicker();
            // getHorariosTurno();
            $("#msg").dialog('destroy');

            $("#msg").attr("title", "sgd - Mensagem");
            $("#msg").dialog({
                autoOpen: false,
                resizable: true,
                height: 240,
                width: 440,
                modal: true
            });

            $("#id_modulo").change(function() {
                $("#reservas").load('fm_getReservas.jsp', {'id_turma': $("#id_turma").val(), 'id_modulo': $(this).val(), 'token': $("#token").val()});
            });

            $(".horariosMan").change(function() {
                var id = $(this).attr("title");
                var selected = $(this).attr('selectedIndex');
                $(".horariosF" + id).attr('selectedIndex', selected);
            });
            $("#alterarSalas").click(function() {
                var params = $(form).serialize();
                $.ajax(
                        {
                            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                            type: "POST",
                            url: "update_reserva_salas.jsp",
                            data: params,
                            beforeSend: function() {
                                // exibe na tela uma
                                // msg de carregando
                                $('#msg').html('<img src="/sgd/imagens/loading.gif"/>');
                                $('#msg').dialog("open");
                            },
                            success: function(txt) {
                                if (txt.indexOf("Erro") < 0) {
                                    $('#msg').html(txt);
                                } else {
                                    $('#msg').html(txt);
                                }
                                $("#list").trigger('reloadGrid');
                            },
                            error: function(txt) {
                                alert('Houve um problema interno. tente novamente mais tarde.');
                            }
                        }
                );
            });
        });

    </script>


    <body>
        <div id="formulario">
            <form name="form" id="form" method="post" action="update.jsp" >
                <input type="hidden" id="operacao" name="operacao" value="">
                <div id="formulario">
                    <fieldset><legend>Dados</legend>
                        <sql:query var="query" dataSource="jdbc/dbo_MicrosoftSQLServer">
                            SELECT  * FROM Turmas
                            where id_turma=?
                            <sql:param value="${param.chave}"/>
                        </sql:query>
                        <c:forEach var="row" items="${query.rows}">
                            <label>Código da Turma: ${row.id_turma}</label>
                            <p><label class="lbInput">Tipo<em>*</em></label>
                                <sql:query var="queryTipo" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  *
                                    FROM tipoturma
                                    order by desc_tipoturma
                                </sql:query>
                                <select name="id_tipoturma" >
                                    <option value="">Selecione uma opção</option>
                                    <c:forEach var="rowTipo" items="${queryTipo.rows}">
                                        <option value="${rowTipo.id_tipoturma}" ${rowTipo.id_tipoturma==row.id_tipoturma?'selected':''}>${rowTipo.desc_tipoturma}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <input name="id_turma" id="id_turma" value="${row.id_turma}" type="hidden">
                            <p><label class="lbInput">Curso<em>*</em></label>
                                <sql:query var="queryCursos" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  Cursos.*
                                    FROM Cursos
                                    order by nome_curso, versao_curso
                                </sql:query>
                                <select name="id_curso" class="required" >
                                    <option value="">Selecione um curso</option>
                                    <c:forEach var="curso" items="${queryCursos.rows}">
                                        <option value="${curso.id_curso}"  ${curso.id_curso==row.id_curso?'selected':''}>${curso.nome_curso}- ${curso.codigo_curso}-V${curso.versao_curso} - ${curso.carga_horaria}h</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <p><label class="lbInput">Unidade<em>*</em></label>
                                <sql:query var="queryUnidade" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  * FROM Unidades
                                </sql:query>
                                <select id="id_unidade" name="id_unidade" class="required">
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="unidade" items="${queryUnidade.rows}">
                                        <option value="${unidade.id_unidade}" ${unidade.id_unidade==row.id_unidade?'selected':''}>${unidade.desc_unidade}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <p><label class="lbInput">Cidade<em>*</em></label>
                                <sql:query var="queryCidade" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    SELECT  * FROM Cidades
                                    order by nome_cidade
                                </sql:query>
                                <select name="id_cidade" class="required">
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="cidade" items="${queryCidade.rows}">
                                        <option value="${cidade.id_cidade}"  ${cidade.id_cidade==row.id_cidade?'selected':''} >${cidade.nome_cidade}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <p><label class="lbInput">Período<em>*</em></label>
                                <fmt:formatDate var="data_inicio" value="${row.inicio_turma}" pattern="dd/MM/yyyy"/>
                                <fmt:formatDate var="data_fim" value="${row.fim_turma}" pattern="dd/MM/yyyy"/>

                                <input type="text" id="data_inicio" name="data_inicio" value="${data_inicio}" size="12" maxlength="12" class="required">
                                <label>a</label>
                                <input type="text" id="data_fim" name="data_fim" value="${data_fim}" size="12" maxlength="12" disabled>

                            </p>
                            <p><label class="lbInput">Código da Turma</label><i>Informe o código da turma vindo do GE</i>
                                <input type="text" id="codigo_turma" name="codigo_turma" value="${row.codigo_turma}" size="12" maxlength="12">
                            </p>
                            <p><label class="lbInput">Número de alunos</label>
                                <input type="text" id="alunos_turma" name="alunos_turma" size="12" maxlength="12" value="${row.alunos_turma}" >
                            </p>
                            <p><label class="lbInput">Cliente</label>
                                <input type="text" id="cliente_turma" name="cliente_turma" size="60" maxlength="60" value="${row.cliente_turma}" >
                            </p>
                            <p><label class="lbInput">Gratuidade</label>
                                <label for="gratuita_turma">Sim</label><input type="radio" id="gratuita_turma" name="gratuita_turma" value="S" ${row.gratuita_turma=='S'?'checked':''}>
                                <label for="gratuita_turma">Não</label><input type="radio" id="gratuita_turma" name="gratuita_turma" value="N" ${row.gratuita_turma=='N'?'checked':''}>
                            </p>
                            <p>
                                <sql:query var="queryRegras" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    select *
                                    from regras
                                    order by desc_regra
                                </sql:query>
                                <label class="lbInput">Regra de alocação</label>
                                <select id="regra" name="id_regra" class="required">
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="regras" items="${queryRegras.rows}">
                                        <option value="${regras.id_regra}" ${regras.id_regra==row.id_regra?'selected':''}>${regras.desc_regra} - ${regras.dias_regra} dias</option>
                                    </c:forEach>
                                </select>

                            </p>
                            <br>
                            <p><label class="lbInput">Turno<em>*</em></label>
                                <sql:query var="queryTurnos" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    select * from Turnos
                                    where situacao_turno='A'
                                </sql:query>
                                <select  name="id_turno" class="required" readonly>
                                    <option value="">Selecione um valor</option>
                                    <c:forEach var="turno" items="${queryTurnos.rows}">
                                        <option value="${turno.id_turno}" ${turno.id_turno==row.id_turno?'selected':''}>${turno.desc_turno}</option>
                                    </c:forEach>
                                </select>
                            </p>
                            <table class="tablescroll" width="100%">
                                <thead>
                                    <tr>
                                        <th>Domingo</th>
                                        <th>Segunda</th>
                                        <th>Terça</th>
                                        <th>Quarta</th>
                                        <th>Quinta</th>
                                        <th>Sexta</th>
                                        <th>Sábado</th>
                                    </tr>
                                </thead>
                                <sql:query var="queryHorarios1" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                    select horarios.* from horarios
                                    where id_turno=?
                                    order by hora_inicio
                                    <sql:param value="${row.id_turno}"/>
                                </sql:query>
                                <tr>
                                    <c:forEach var="dia" begin="1" end="7">
                                        <td>                                    
                                            <select id="horariosMan" title="${dia}" name="horariosMan" class="horariosMan" >                                    
                                                <option value="">Horário</option>                                                                
                                                <c:forEach var="rowHorarios" items="${queryHorarios1.rows}">                                                            
                                                    <option value="${rowHorarios.id_horario}_${dia}" 
                                                            ${rowHorarios.dia==dia?'selected':''}>${rowHorarios.hora_inicio} - ${rowHorarios.hora_fim}</option>                                                                
                                                </c:forEach>    
                                            </select>      
                                        </td>
                                    </c:forEach>
                                </tr>
                            </table>

                            <sql:query var="queryModulos" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                select ordem_componente, desc_componente,m.id_modulo,c.id_componente from modulos m
                                inner join grades g on g.id_modulo=m.id_modulo and g.id_curso=m.id_curso
                                inner join componentes c on g.id_componente=c.id_componente
                                where m.id_curso=?
                                <sql:param value="${row.id_curso}"/>
                                order by ordem_componente
                            </sql:query>
                            <br>

                            <div id="horarios">
                                <table class="tablescroll" width="100%">
                                    <thead>
                                        <tr>
                                            <th>Componente</th>
                                            <th>Domingo</th>
                                            <th>Segunda</th>
                                            <th>Terça</th>
                                            <th>Quarta</th>
                                            <th>Quinta</th>
                                            <th>Sexta</th>
                                            <th>Sábado</th>
                                        </tr>
                                    </thead>
                                    <c:forEach var="rowModulos" items="${queryModulos.rows}">                                        
                                        <div>


                                            <tr>
                                                <td>
                                                    <b>${rowModulos.ordem_componente} - ${rowModulos.desc_componente}</b>
                                                    <input id="id_modulo" type="hidden" name="id_modulo" value="${rowModulos.id_modulo}">

                                                </td>
                                                <c:forEach var="dia" begin="1" end="7">
                                                    <td>
                                                        <sql:query var="queryHorarios" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                                            select horarios.*, dia from horarios
                                                            left join horarios_turmas
                                                            on horarios.id_horario=horarios_turmas.id_horario and dia=? and id_turma=? and id_modulo=? and id_componente=?
                                                            where id_turno=?
                                                            order by hora_inicio
                                                            <sql:param value="${dia}"/>
                                                            <sql:param value="${row.id_turma}"/>
                                                            <sql:param value="${rowModulos.id_modulo}"/>
                                                            <sql:param value="${rowModulos.id_componente}"/>
                                                            <sql:param value="${row.id_turno}"/>
                                                        </sql:query>

                                                        <select id="horarios" name="horarios" class="horariosF${dia}">                                    
                                                            <option value="">horário</option>                                                                
                                                            <c:forEach var="rowHorarios" items="${queryHorarios.rows}">                                                            
                                                                <option value="${rowModulos.id_modulo}_${rowModulos.id_componente}_${rowHorarios.id_horario}_${dia}" 
                                                                        ${rowHorarios.dia==dia?'selected':''}>${rowHorarios.hora_inicio} - ${rowHorarios.hora_fim}</option>                                                                
                                                            </c:forEach>    
                                                        </select>      
                                                    </td>
                                                </c:forEach>
                                            </tr>

                                        </div>                
                                    </c:forEach>
                                </table>
                            </div>                                


                            <div id="grade">
                                <table id="calendario"></table>
                                <div id="pager_calendario"></div>
                                <br>
                                <div>
                                    <sql:query var="querySalas" dataSource="jdbc/dbo_MicrosoftSQLServer">
                                        select s.*, desc_tiposala, desc_unidade from Salas s
                                        inner join TipoSalas t on s.id_tiposala=t.id_tiposala
                                        inner join unidades u on s.id_unidade=u.id_unidade
                                        where situacao_tiposala='A'
                                        and (s.id_unidade=? or ?=0)
                                        <sql:param value="${row.id_unidade}"/>
                                        <sql:param value="${row.id_unidade}"/>
                                        order by desc_sala
                                    </sql:query>
                                    <b>Sala para todos os componentes: </b> <br>
                                    <select name="id_sala" id="salas_geral">
                                        <option value="">Selecione uma sala</option>
                                        <c:forEach var="s" items="${querySalas.rows}">
                                            <option value="${s.id_sala}">
                                                ${s.desc_sala} - ${s.desc_unidade}
                                            </option>
                                        </c:forEach>
                                    </select>
                                    <input class="submit" type="button" id="alterarSalas" value="Alterar Salas">
                                </div>
                                <br>
                                <table id="list"></table>
                                <div id="pager"></div>
                                <br>
                                <table id="salas"></table>
                                <div id="pager_salas"></div>

                            </div>
                        </c:forEach>
                        <p>
                            <input class="submit" type="submit" id="salvar" value="Salvar" onclick="clicar('salvar')">
                            <input id="ordenar" class="submit" type="submit" onclick="clicar('ordenar')" value="Ordenar">
                            <input id="estruturar" class="submit" type="submit" onclick="clicar('estruturar')" value="Reestruturar Turma">
                            <input class="submit" type="button" value="Remover" onclick="remover(document.forms[0])">
                            <input class="submit" type="button" value="Liberar para Alocação" onclick="alocarTurma(document.forms[0])">
                            <input class="submit" type="button" id="consultar" name="consultar" value="Consultar" onclick="listar('fm_lista_turmas.jsp')">
                        </p>
                        <div id="ajax_dados" style="display:block">
                        </div>
                        <div id="msg" style="display:none"></div>
                    </fieldset>
                </div>
                <input type="hidden" id="token" name="token" value="${sessionScope.token}" /> </form>
        </div>
    </body>
    <script type="text/javascript">
        var lastsel2;
        var lastselsalas;
        var lastselcal;

        $(function() {
            $("#list").jqGrid({
                url: 'fm_getGrade.jsp?token=${sessionScope.token}&id_turma=${param.chave}',
                datatype: 'xml',
                mtype: 'POST',
                colNames: ['Ordem', 'Módulo', 'Componente', 'C. Horária', 'Início', 'Fim', 'Sala', 'Sub-Turma', 'Copiar?', 'Regra'],
                colModel: [
                    {name: 'ordem', index: 'ordem', width: 30, align: 'center', edittype: "text", editable: true, sortable: false, editrules: {required: true}},
                    {name: 'desc_modulo', index: 'desc_modulo', width: 90, edittype: "text", editable: false, sortable: false},
                    {name: 'desc_componente', index: 'desc_componente', width: 180, align: 'center', edittype: "text", editable: false, sortable: false},
                    {name: 'carga_horaria', index: 'carga_horaria', width: 50, align: 'center', edittype: "text", editable: true, sortable: false, editrules: {required: true}},
                    {name: 'data_inicio', index: 'data_inicio', width: 50, align: 'center', edittype: "text", editable: true, sortable: false, editrules: {required: true}},
                    {name: 'data_fim', index: 'data_fim', align: 'center', width: 50, edittype: "text", sortable: false, editable: true, editrules: {required: true}},
                    {name: 'id_sala', index: 'id_sala', align: 'center', width: 150, sortable: false,
                        editable: true, edittype: "select",
                        editoptions: {dataUrl: '../Alocacoes/fm_getSalas.jsp?token=${sessionScope.token}&id_unidade=' + $("#id_unidade").val()},
                        editrules: {required: true}
                    },
                    {name: 'subturma', index: 'subturma', width: 30, align: 'center', edittype: "text", editable: true, sortable: false},
                    {name: 'copiar', index: 'copiar', hidden: true, edittype: "checkbox", editable: true, sortable: false
                        , editoptions: {value: "Sim:Nao"}, editrules: {edithidden: true}},
                    {name: 'id_regra_horarios', index: 'id_regra_horarios', align: 'center', width: 250, sortable: false, hidden: true,
                        editable: true, edittype: "select",
                        editoptions: {dataUrl: 'getRegraHorarios.jsp?token=${sessionScope.token}'}, editrules: {required: false, edithidden: true}
                    }
                ],
                onSelectRow: function(id) {
                    if (id && id !== lastsel2) {
                        jQuery('#list').jqGrid('restoreRow', lastsel2);
                        jQuery('#list').jqGrid('editRow', id, true);

                        lastsel2 = id;
                    }
                    jQuery("#salas").jqGrid('setGridParam', {editurl: "../Alocacoes/update.jsp?token=${sessionScope.token}&id_reserva=" + lastsel2});
                    if (id == null) {
                        id = 0;
                        if (jQuery("#salas").jqGrid('getGridParam', 'records') > 0)
                        {
                            jQuery("#salas").jqGrid('setGridParam', {url: "fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id=" + id, page: 1})
                                    .trigger('reloadGrid');
                        }
                    } else {
                        jQuery("#salas").jqGrid('setGridParam', {url: "fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id=" + id, page: 1})
                                .trigger('reloadGrid');
                    }

                },
                pager: '#pager',
                autowidth: true,
                height: 200,
                rowNum: 200,
                pgbuttons: false,
                pgtext: false,
                pginput: false,
                viewrecords: true,
                sortname: 'ordem',
                sortorder: 'desc',
                editurl: "update_reserva.jsp?token=${sessionScope.token}",
                caption: 'Componentes'
            });

            jQuery("#list").jqGrid('navGrid', '#pager', {add: false, del: true, search: false, edittext: 'Editar'}, //options
            {width: 560, reloadAfterSubmit: true}, // edit options
            {width: 560, reloadAfterSubmit: true}, // add options
            {reloadAfterSubmit: true}, // del options
            {} // search options
            );

            $("#salas").jqGrid({
                url: 'fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id=0',
                datatype: 'xml',
                mtype: 'POST',
                colNames: ['Data', 'Hora Inicial', 'Hora Final', 'Sala', 'Sub-Turma', 'Situação', 'Otimizado'],
                colModel: [
                    {name: 'data_alocacao', index: 'data_alocacao', width: 38, edittype: "text", editable: true, editrules: {required: true}, editoptions: {size: 12}, sortable: false, align: "center"},
                    {name: 'hora_inicio', index: 'hora_inicio', width: 30, align: 'center', edittype: "text", editable: true, editrules: {required: true}, sortable: false},
                    {name: 'hora_fim', index: 'hora_fim', width: 30, align: 'center', edittype: "text", editable: true, editrules: {required: true}, sortable: false},
                    {name: 'id_sala', index: 'id_sala', align: 'center', width: 150, sortable: false, editoptions: {size: 60},
                        editable: true, edittype: "select",
                        editoptions:{dataUrl: '../Alocacoes/fm_getSalas.jsp?token=${sessionScope.token}&id_unidade=0'}
                    },
                    {name: 'subturma', index: 'subturma', width: 20, align: 'center', edittype: "text", editable: true, sortable: false},
                    {name: 'situacao', index: 'situacao', width: 150, align: 'center', edittype: "text", editable: false, sortable: false}
                    ,
                    {name: 'otimizado', index: 'otimizado', align: 'center', width: 20,
                        edittype: "select", editable: true,
                        editoptions: {value: "S:Sim;N:Não"},
                        sortable: false, editable:true},
                ],
                onSelectRow: function(id) {
                    if (id && id !== lastselsalas) {
                        jQuery('#salas').jqGrid('restoreRow', lastselsalas);
                        jQuery('#salas').jqGrid('editRow', id, true);

                        lastselsalas = id;
                    }
                },                
                pager: '#pager_salas',
                autowidth: true,
                height: 200,
                rowNum: 200,
                viewrecords: true,
                pgbuttons: false,
                pgtext: false,
                pginput: false,
                rownumbers: true,
                sortname: 'data_alocacao',
                sortorder: 'desc',
                editurl: "../Alocacoes/update.jsp?token=${sessionScope.token}",
                caption: 'Salas e Horários'
            });

            jQuery("#salas").jqGrid('navGrid', '#pager_salas', {search: false, addtext: 'Inserir', edittext: 'Editar', deledit: 'Remover'}, //options
            {width: 580, reloadAfterSubmit: true}, // edit options
            {width: 580, reloadAfterSubmit: true}, // add options
            {reloadAfterSubmit: true}, // del options
            {} // search options
            );



            $("#calendario").jqGrid({
                url: 'fm_getCalendarioTurma.jsp?token=${sessionScope.token}&id_turma=${param.chave}',
                datatype: 'xml',
                mtype: 'POST',
                colNames: ['Dia', 'Executa?'],
                colModel: [
                    {name: 'data_calendario', index: 'data_calendario', width: 50, align: 'center',
                        edittype: "text", editable: true, sortable: false, editrules: {required: true}},
                    {name: 'diautil_calendario', index: 'diautil_calendario', width: 20, align: 'center',
                        edittype: "select", editable: true, sortable: false
                        , editoptions: {value: "S:Sim;N:Não"}},
                ],
                onSelectRow: function(id) {
                    if (id && id !== lastselcal) {
                        jQuery('#calendario').jqGrid('restoreRow', lastselcal);
                        jQuery('#calendario').jqGrid('editRow', id, true);

                        lastselcal = id;
                    }
                },
                pager: '#pager_calendario',
                width: 330,
                height: 100,
                rowNum: 'auto',
                pgbuttons: false,
                pgtext: false,
                pginput: false,
                viewrecords: true,
                sortname: 'data_calandario',
                sortorder: 'desc',
                editurl: "update_calendario_turma.jsp?token=${sessionScope.token}&id_turma=${param.chave}",
                caption: 'Calendário'
            });

            jQuery("#calendario").jqGrid('navGrid', '#pager_calendario', {add: true, del: true, search: false}, //options
            {width: 300, reloadAfterSubmit: true}, // edit options
            {width: 300, reloadAfterSubmit: true}, // add options
            {reloadAfterSubmit: true}, // del options
            {} // search options
            );

        });

        function reloadGrid(id) {
            jQuery("#salas").jqGrid('setGridParam', {url: "fm_getAlocacoesSalas.jsp?token=${sessionScope.token}&id=" + id, page: 1})
                    .trigger('reloadGrid');
        }


    </script>
</html>
